package org.ubc.cs410.disposal2020.server;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ubc.cs410.disposal2020.Game;
import org.ubc.cs410.disposal2020.GameFactory;
import org.ubc.cs410.disposal2020.NoActiveGameException;
import org.ubc.cs410.disposal2020.Player;

import com.google.gwt.core.client.GWT;

/*
 * Servlet for generating joining.html
 */

public class JoinGameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		try {
			// If user already has an active game, redirect to it.
			Game game = GameFactory.getCurrentGame();
			if (game.isActive()) {
				resp.sendRedirect(resp.encodeRedirectURL("/game/"+game.getSlug()));
			} else {
				resp.sendRedirect(resp.encodeRedirectURL("/waiting.html"));
			}
			return;
		} catch (NoActiveGameException nage) {
			// Template data
			Map<String, Object> root = new HashMap<String, Object>();

			// Page title
			root.put("title", "Join a game");

			// Do the rendering
			ServletUtils.renderTemplate(getServletContext(), root, "JoinGame.ftl",
					resp, req.getRequestURI());
		}
	}
}
